package com.bw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

public class DwdTrafficUniqueVisitorDetail {
    public static void main(String[] args) throws Exception {
        //环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //从kafka dwd_traffic_page_log主题中读取数据封装为流
        String topic="dwd_traffic_page_log";
        String groupId="dwd_traffic_user_jump_detail";
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> pageLog = env.addSource(kafkaConsumer);

        //转换结构
        SingleOutputStreamOperator<JSONObject> mappedStream = pageLog.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObj = JSONObject.parseObject(s);
                    collector.collect(jsonObj);
                } catch (Exception e) {
                    System.out.println("脏数据" + s);
                }
            }
        });


//        过滤last_page_id  不为null的数据
        SingleOutputStreamOperator<JSONObject> firstPageStream = mappedStream.filter(x -> x
                .getJSONObject("page")
                .getString("last_page_id") == null

        );
        //按照mid分组
        KeyedStream<JSONObject, String> keyedStream = firstPageStream
                .keyBy(x -> x.getJSONObject("common").getString("mid"));

        //通过Flink状态编程过滤独立访客记录
        keyedStream.filter(
                new RichFilterFunction<JSONObject>() {
                    private ValueState<String> lastVisitDt;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_visit_dt", String.class);

                        //配置状态的生命周期
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig
                                .newBuilder(Time.days(1L))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build());
                        this.lastVisitDt  = getRuntimeContext().getState(valueStateDescriptor);
                    }


                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        String visitDt = DateFormatUtil.toDate(jsonObject.getLong("ts"));
                        //null !=null
                        String lastDt = lastVisitDt.value();
                        if(lastDt==null || !lastDt.equals(visitDt)){
                            lastVisitDt.update(visitDt);
                            return true;
                        }
                        return false;
                    }

                }

        );

        //将独立访客数据写入
        //Kafka dwd_traffic_unique_visitor_detail  主题
        String targetTopic="dwd_traffic_unique_visitor_detail";
        firstPageStream.print(">>>>>>>>>>>>>>>>>>>>>>>>>");
        FlinkKafkaProducer<String> KafkaProducer = MyKafkaUtil.getFlinkKafkaProducer(targetTopic);
        firstPageStream.map(x->x.toJSONString()).addSink(KafkaProducer);


        //启动任务
        env.execute();
    }
}
